import { Injectable } from '@nestjs/common'
@Injectable()
export class YunService {
  getSearchOptions() {
    const brand = [
      { label: '所有品牌', value: '' },
      { label: 'KFC', value: 'KFC' },
      { label: '星巴克', value: '星巴克' },
    ]

    const partition = [
      { label: '所有分区', value: '' },
      { label: '北京区', value: '北京区' },
      { label: '上海区', value: '上海区2' },
    ]

    const shop = [
      { label: '所有店铺', value: '' },
      { label: '店铺1', value: '店铺1' },
      { label: '店铺2', value: '店铺2' },
    ]

    const source = [
      { label: '所有来源', value: '' },
      { label: '美团', value: '美团' },
      { label: '饿了么', value: '饿了么' },
    ]

    return {
      brand,
      partition,
      shop,
      source,
    }
  }
  generateDays(days: string) {
    const daysArray = []
    const today = new Date()

    for (let i = -1; i <= Number(days) + 1; i++) {
      const date = new Date(today)
      date.setDate(today.getDate() - (i + 1))
      const day = `${date.getMonth() + 1}.${date.getDate()}`
      daysArray.push(day)
    }
    daysArray.reverse()
    return daysArray
  }
  getTotalPriceByDate(dateStr, arr) {
    const dateTimeStr = dateStr.includes('-')
      ? dateStr
      : `${new Date().getFullYear()}-${dateStr}`
    const targetDate = new Date(dateTimeStr)
    const targetDay = targetDate.getDate()
    const targetMonth = targetDate.getMonth() + 1
    const targetYear = targetDate.getFullYear()
    let totalPrice = 0
    for (let i = 0; i < arr.length; i++) {
      const orderDate = new Date(arr[i].DealTime)
      const orderDay = orderDate.getDate()
      const orderMonth = orderDate.getMonth() + 1
      const orderYear = orderDate.getFullYear()
      if (
        targetYear === orderYear &&
        targetMonth === orderMonth &&
        targetDay === orderDay
      ) {
        totalPrice += arr[i].price
      }
    }
    return totalPrice
  }


  OrderStatistics(timeRange: string, orders: any) {
    const date = this.generateDays(timeRange)
    const totalPrices = date.map((d) => this.getTotalPriceByDate(d, orders))
    const totalOrderCount = orders.length
    const meituanTotal = date.map((d) => this.getTotalPriceByDate(d, orders))
    const validOrders = orders.filter((order) => order.status === '已送达')
    const PricePrecent = orders.reduce(
      (sum, order) => sum + (order.price - order.numsum),
      0,
    )

    const meituanCustomers = orders.filter(
      (order) => order.origin === '美团',
    ).length
    const elmCustomers = orders.filter(
      (order) => order.origin === '饿了么',
    ).length
    const validOrderCount = validOrders.length
    const actualAmount = totalPrices.reduce((sum, price) => sum + price, 0)
    const actualPayAmount = orders.reduce(
      (sum, order) => sum + order.price - order.numsum,
      0,
    )
    const perCapitaConsumption = actualAmount / totalOrderCount
    const meituanNewCustomers = {}
    const meituanOldCustomers = {}
    const elmNewCustomers = {}
    const elmOldCustomers = {}

    orders.forEach((order) => {
      if (order.origin === '美团') {
        if (meituanNewCustomers[order.seller]) {
          meituanOldCustomers[order.seller] = true
          delete meituanNewCustomers[order.seller]
        } else if (!meituanOldCustomers[order.seller]) {
          meituanNewCustomers[order.seller] = true
        }
      } else if (order.origin === '饿了么') {
        if (elmNewCustomers[order.seller]) {
          elmOldCustomers[order.seller] = true
          delete elmNewCustomers[order.seller]
        } else if (!elmOldCustomers[order.seller]) {
          elmNewCustomers[order.seller] = true
        }
      }
    })
    const newCustomers = {}
    const oldCustomers = {}
    orders.forEach((order) => {
      if (order.seller) {
        if (newCustomers[order.seller]) {
          oldCustomers[order.seller] = true
        } else {
          newCustomers[order.seller] = true
        }
      }
    })

    // 返回统计数据对象
    return {
      PaidInAmount: actualAmount,
      TotalPaid: actualPayAmount,
      SalesOrderNumber: totalOrderCount,
      PerCapitaConsumptionAmount: validOrderCount,
      meituanNumber: meituanCustomers,
      elmNumber: elmCustomers,
      PricePrecent: PricePrecent,
      validOrderNumber: perCapitaConsumption,
      meituanNewCustomers: Object.keys(meituanNewCustomers).length,
      meituanOldCustomers: Object.keys(meituanOldCustomers).length,
      elmNewCustomers: Object.keys(elmNewCustomers).length,
      elmOldCustomers: Object.keys(elmOldCustomers).length,
      NewCustomer: Object.keys(newCustomers).length,
      patron: Object.keys(oldCustomers).length,
    }
  }
  filterOrders(
    orders: any[],
    filters: {
      brand?: string
      partition?: string
      shop?: string
      source?: string
      startDate?: string
      endDate?: string
    },
  ): any[] {
    return orders.filter((order) => {
      if (filters.brand && order.brand !== filters.brand) {
        return false
      }
      if (filters.partition && order.partition !== filters.partition) {
        return false
      }
      if (filters.shop && order.shop !== filters.shop) {
        return false
      }
      if (filters.source && order.origin !== filters.source) {
        return false
      }
      if (filters.startDate && filters.endDate) {
        const orderDate = new Date(order.DealTime)
        const startDate = new Date(filters.startDate)
        const endDate = new Date(filters.endDate)
        if (orderDate < startDate || orderDate > endDate) {
          return false
        }
      }
      return true
    })
  }
}
